//
//  PlayerDetailViewController.m
//  SHEL
//
//  Created by Jennifer Guriel on 11/15/11.
//  Copyright 2011 Washington University. All rights reserved.
//

#import "PlayerDetailViewController.h"


@implementation PlayerDetailViewController

@synthesize hits;
@synthesize thits;
@synthesize temperature;
@synthesize dataForPlot;
@synthesize tempPlot;
@synthesize traumaPlot;
@synthesize hitsPlot;
@synthesize graphView;
@synthesize dataToPlot;
@synthesize datesToPlot;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}


-(id)initWithNibNameAndIndex:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil index:(int)index name:(NSString*)name history:(NSMutableArray*)historyInput trauma:(NSMutableArray*)traumaInput
{
	[self initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
	
	self.title = name;
	history = historyInput;
	trauma = traumaInput;
	UIScrollView *tempScrollView=(UIScrollView *)self.view;
	tempScrollView.contentSize=CGSizeMake(320,510);
	return self;
}

-(int) dateOffset:(NSDate*)referenceDate rec:(NSString*)recordDateStr {
	//NSLog(@"1) %@", recordDateStr);
	
	NSDateFormatter *date_formater=[[NSDateFormatter alloc] init];
	[date_formater setDateFormat:@"YYY-MM-dd"];
	NSDate* recordDate = [date_formater dateFromString:recordDateStr];
	//NSLog(@"2) %@",[date_formater stringFromDate:referenceDate]);
	
	int diff = [recordDate timeIntervalSinceDate:referenceDate] / 60 / 60 / 24;
	//NSLog(@"3) %d", diff);
	
	[date_formater release];
	
	return diff+1;
}

-(NSDate*) getDateFromString:(NSString*)recordDateStr {
	
	NSDateFormatter *date_formater=[[NSDateFormatter alloc] init];
	[date_formater setDateFormat:@"YYY-MM-dd"];
	NSDate* recordDate = [date_formater dateFromString:recordDateStr];
	
	return recordDate;
}

-(BOOL) recordIsToday:(NSString*)record {
	BOOL recordIsToday = FALSE;
	
	NSString* recordDate = [[record objectForKey:@"date"] substringToIndex:10];
	//NSLog(@"1) %@", historyDate);
	
	NSDateFormatter *date_formater=[[NSDateFormatter alloc] init];
	[date_formater setDateFormat:@"YYY-MM-dd"];
	NSString* sDate = [date_formater stringFromDate:[NSDate date]];
	[date_formater release];
	//NSLog(@"2) %@",sDate);
	
	if ([recordDate isEqualToString:sDate])
	{
		recordIsToday = TRUE;
		//NSLog(@"match!");
	}
	return recordIsToday;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	dataForPlot = [[NSMutableArray alloc] init];
	hitsPlot = [[NSMutableArray alloc] init];
	traumaPlot = [[NSMutableArray alloc] init];
	tempPlot = [[NSMutableArray alloc] init];
	
	// Set the labels
	NSString *hitString;
	NSString *thitString;
	NSString *temperatureString;
	
	if (history != nil && [history count] > 0)
	{
		// Verify the history record is for today
		int totalHits = 0;
		float currentTemp = 0.0;
		if ([self recordIsToday:[history objectAtIndex:0]]) 
		{
			totalHits = [[[history objectAtIndex:0] objectForKey:@"hits"] intValue];
			currentTemp = [[[history objectAtIndex:0] objectForKey:@"temperature"] floatValue];
		}
		hitString = [NSString stringWithFormat:@"%d", totalHits];
		temperatureString = [NSString stringWithFormat:@"%.1f", currentTemp];
	}
	else 
	{
		hitString = [NSString stringWithFormat:@"N/A"];
		temperatureString = [NSString stringWithFormat:@"N/A"];
	}
	
	if (trauma != nil && [trauma count] > 0)
	{
		// Loop through all of the trauma records and see if any are for today
		int traumaToday = 0;
		for (int i = 0; i<[trauma count]; ++i) 
		{
			if ([self recordIsToday:[trauma objectAtIndex:i]]) 
			{
				traumaToday++;
			}
		}
		thitString = [NSString stringWithFormat:@"%d", traumaToday];
	}
	else 
	{
		thitString = [NSString stringWithFormat:@"N/A"];
	}
	
	thits.text = [NSString stringWithFormat:@"Traumatic Hits: %@", thitString];
	hits.text = [NSString stringWithFormat:@"Total Hits: %@", hitString];
	temperature.text = [NSString stringWithFormat:@"Temperature: %@", temperatureString];
	
	
	int numberOfDays = 30; // 10
	int dayInterval = 6;   // 2
	int orthDayCoord = 6;  // 2
	
	// If you make sure your dates are calculated at noon, you shouldn't have to 
    // worry about daylight savings. If you use midnight, you will have to adjust
    // for daylight savings time.
	NSTimeInterval oneDay = 24 * 60 * 60;
    NSDate* refDate = [[NSDate date] addTimeInterval:-(numberOfDays+dayInterval)*oneDay];
	
    // Create graph from theme
    graph = [(CPTXYGraph *)[CPTXYGraph alloc] initWithFrame:CGRectZero];
	CPTTheme *theme = [CPTTheme themeNamed:kCPTSlateTheme];
	[graph applyTheme:theme];
	
	graph.paddingLeft = 10.0;
	graph.paddingTop = 10.0;
	graph.paddingRight = 10.0;
	graph.paddingBottom = 10.0;
	
	CPTGraphHostingView *hostingView = (CPTGraphHostingView *)graphView;//self.view;
    hostingView.collapsesLayers = NO; // Setting to YES reduces GPU memory usage, but can slow drawing/scrolling
    [hostingView setHostedGraph:graph];
    
    // Setup scatter plot space
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
    NSTimeInterval xLow = 0.0f;
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(xLow) length:CPTDecimalFromFloat(oneDay*(numberOfDays+(1.5*dayInterval)))];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(-20.0) length:CPTDecimalFromFloat(130.0)];
    
    // Axes
	CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
    CPTXYAxis *x = axisSet.xAxis;
    x.majorIntervalLength = CPTDecimalFromFloat(oneDay*dayInterval);
    x.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0.0");
    x.minorTicksPerInterval = 0;
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    //dateFormatter.dateStyle = kCFDateFormatterShortStyle;
    [dateFormatter setDateFormat:@"MM-dd"];
	CPTTimeFormatter *timeFormatter = [[[CPTTimeFormatter alloc] initWithDateFormatter:dateFormatter] autorelease];
    timeFormatter.referenceDate = refDate;
    x.labelFormatter = timeFormatter;
	
    CPTXYAxis *y = axisSet.yAxis;
    y.majorIntervalLength = CPTDecimalFromString(@"20.0");
    y.minorTicksPerInterval = 0;
    y.orthogonalCoordinateDecimal = CPTDecimalFromFloat(oneDay*orthDayCoord);
	
	// Add plots to the graph
	// one per data type
	//
	// Create a plot that uses the data source method
	dataSourceLinePlot1 = [[CPTScatterPlot alloc] init];
	dataSourceLinePlot1.identifier = @"Trauma Plot";
	
	CPTMutableLineStyle *lineStyle1 = [[dataSourceLinePlot1.dataLineStyle mutableCopy] autorelease];
	lineStyle1.lineWidth = 3.f;
	lineStyle1.lineColor = [CPTColor redColor];
	dataSourceLinePlot1.dataLineStyle = lineStyle1;
	
	dataSourceLinePlot1.dataSource = self;
	[graph addPlot:dataSourceLinePlot1];
	
	// Create a plot that uses the data source method
	dataSourceLinePlot2 = [[CPTScatterPlot alloc] init];
	dataSourceLinePlot2.identifier = @"Hits Plot";
	
	CPTMutableLineStyle *lineStyle2 = [[dataSourceLinePlot2.dataLineStyle mutableCopy] autorelease];
	lineStyle2.lineWidth = 3.f;
	lineStyle2.lineColor = [CPTColor yellowColor];
	dataSourceLinePlot2.dataLineStyle = lineStyle2;
	
	dataSourceLinePlot2.dataSource = self;
	[graph addPlot:dataSourceLinePlot2];
	
	// Create a plot that uses the data source method
	dataSourceLinePlot3 = [[CPTScatterPlot alloc] init];
	dataSourceLinePlot3.identifier = @"Temp Plot";
	
	CPTMutableLineStyle *lineStyle3 = [[dataSourceLinePlot3.dataLineStyle mutableCopy] autorelease];
	lineStyle3.lineWidth = 3.f;
	lineStyle3.lineColor = [CPTColor orangeColor];
	dataSourceLinePlot3.dataLineStyle = lineStyle3;
	
	dataSourceLinePlot3.dataSource = self;
	[graph addPlot:dataSourceLinePlot3];
	
    // Add some initial data
	NSMutableArray *contentArray;
	
	contentArray = [NSMutableArray arrayWithCapacity:[history count]];
	for (int j=0; j<[history count]; ++j) {
		int diff = [self dateOffset:refDate rec:[[[history objectAtIndex:j] objectForKey:@"date"] substringToIndex:10]];
		int hitsForRecord = [[[history objectAtIndex:j] objectForKey:@"hits"] intValue];
		
		// Use the date diff from starting refDate -- if in the window, add to dataset
		if (diff >= 0 && diff > dayInterval) { 
			id x = [NSNumber numberWithFloat:diff*oneDay];
			id y = [NSNumber numberWithFloat:hitsForRecord];
			[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, @"x", y, @"y", nil]];
		}
	}
	self.hitsPlot = contentArray;
	
	contentArray = [NSMutableArray arrayWithCapacity:[history count]];
	for (int j=0; j<[history count]; ++j) {
		int diff = [self dateOffset:refDate rec:[[[history objectAtIndex:j] objectForKey:@"date"] substringToIndex:10]];
		float tempForRecord = [[[history objectAtIndex:j] objectForKey:@"temperature"] floatValue];
		
		// Use the date diff from starting refDate -- if in the window, add to dataset
		if (diff >= 0 && diff > dayInterval) {
			id x = [NSNumber numberWithFloat:diff*oneDay];
			id y = [NSNumber numberWithFloat:tempForRecord];
			[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, @"x", y, @"y", nil]];
		}
	}
	self.tempPlot = contentArray;
	
	// Trauma is a bit different from the others
	// First gather the trauma data into the traumaForDisplay
	NSMutableDictionary* traumaForDisplay = [[NSMutableDictionary alloc] init];
	for (int j=0; j<[trauma count]; j++)
	{
		NSString* recordDate = [[[trauma objectAtIndex:j] objectForKey:@"date"] substringToIndex:10];
		
		if ([traumaForDisplay objectForKey:recordDate] != nil)
		{
			NSNumber* currentValue = [traumaForDisplay objectForKey:recordDate];
			NSNumber* newValue = [NSNumber numberWithInt:[currentValue intValue]+10];
			[traumaForDisplay setObject:newValue forKey:recordDate];
		}
		else {
			NSNumber* newValue = [NSNumber numberWithInt:10];
			[traumaForDisplay setObject:newValue forKey:recordDate];
		}
	}
	
	NSArray *myKeys = [traumaForDisplay allKeys];
	NSArray *sortedKeys = [myKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
	
	contentArray = [NSMutableArray arrayWithCapacity:[trauma count]];
	for (NSString *key in sortedKeys) 
	{
		int diff = [self dateOffset:refDate rec:key];
		float traumaCount = [[traumaForDisplay objectForKey:key] floatValue];
		if (diff >= 0 && diff > dayInterval) {
			id x = [NSNumber numberWithFloat:diff*oneDay];
			id y = [NSNumber numberWithFloat:traumaCount];
			[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, @"x", y, @"y", nil]];
		}
	}
	[traumaForDisplay release];
	
	self.traumaPlot = contentArray;
}


-(void)updatePlot
{
}

/*-(void)changePlotRange 
{
    // Setup plot space
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat(3.0 + 2.0*rand()/RAND_MAX)];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat(3.0 + 2.0*rand()/RAND_MAX)];
}*/

#pragma mark -
#pragma mark Plot Data Source Methods

-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
	if ([(NSString *)plot.identifier isEqualToString:@"Hits Plot"] && self.hitsPlot != nil)
	{
		return [self.hitsPlot count];
	}
	else if ([(NSString *)plot.identifier isEqualToString:@"Trauma Plot"] && self.traumaPlot != nil)
	{
		return [self.traumaPlot count];
	}
	else if ([(NSString *)plot.identifier isEqualToString:@"Temp Plot"] && self.tempPlot != nil)
	{
		return [self.tempPlot count];
	}
	else {
		return 0;
	}
}

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index 
{
	NSNumber *num;
	if ([(NSString *)plot.identifier isEqualToString:@"Hits Plot"])
	{
		num = [[hitsPlot objectAtIndex:index] valueForKey:(fieldEnum == CPTScatterPlotFieldX ? @"x" : @"y")];
	}
	else if ([(NSString *)plot.identifier isEqualToString:@"Trauma Plot"])
	{
		num = [[traumaPlot objectAtIndex:index] valueForKey:(fieldEnum == CPTScatterPlotFieldX ? @"x" : @"y")];
	}
	else if ([(NSString *)plot.identifier isEqualToString:@"Temp Plot"])
	{
		num = [[tempPlot objectAtIndex:index] valueForKey:(fieldEnum == CPTScatterPlotFieldX ? @"x" : @"y")];
	}
	else {
		num = [[dataForPlot objectAtIndex:index] valueForKey:(fieldEnum == CPTScatterPlotFieldX ? @"x" : @"y")];
	}
	
    return num;
}


-(IBAction) dataSegCtrlIndexChanged
{
	NSArray* plots = [graph allPlots];;
	BOOL alreadyAdded = FALSE;
	BOOL alreadyAdded2 = FALSE;
	BOOL alreadyAdded3 = FALSE;
	
	switch (self.dataToPlot.selectedSegmentIndex) {
		case 0:
			for (CPTScatterPlot* p in plots)
			{
				if (p == dataSourceLinePlot1) {
					alreadyAdded = TRUE;
				}
				else if (p == dataSourceLinePlot2)
				{
					alreadyAdded2 = TRUE;
				}
				else if (p == dataSourceLinePlot3)
				{
					alreadyAdded3 = TRUE;
				}
			}
			if (!alreadyAdded) {
				[graph addPlot:dataSourceLinePlot1];
			}
			if (!alreadyAdded2) {
				[graph addPlot:dataSourceLinePlot2];
			}
			if (!alreadyAdded3) {
				[graph addPlot:dataSourceLinePlot3];
			}
			break;
			
		case 1:
			for (CPTScatterPlot* p in plots)
			{
				if (p == dataSourceLinePlot1) {
					alreadyAdded = TRUE;
				}
				else if (p == dataSourceLinePlot2)
				{
					[graph removePlot:dataSourceLinePlot2];
				}
				else if (p == dataSourceLinePlot3)
				{
					[graph removePlot:dataSourceLinePlot3];
				}
			}
			if (!alreadyAdded) {
				[graph addPlot:dataSourceLinePlot1];
			}
			break;
	 
		case 2:
			for (CPTScatterPlot* p in plots)
			{
				if (p == dataSourceLinePlot1) {
					[graph removePlot:dataSourceLinePlot1];
				}
				else if (p == dataSourceLinePlot2)
				{
					alreadyAdded = TRUE;
				}
				else if (p == dataSourceLinePlot3)
				{
					[graph removePlot:dataSourceLinePlot3];
				}
			}
			if (!alreadyAdded) {
				[graph addPlot:dataSourceLinePlot2];
			}
			break;

		case 3:
			for (CPTScatterPlot* p in plots)
			{
				if (p == dataSourceLinePlot1) {
					[graph removePlot:dataSourceLinePlot1];
				}
				else if (p == dataSourceLinePlot2)
				{
					[graph removePlot:dataSourceLinePlot2];
				}
				else if (p == dataSourceLinePlot3)
				{
					alreadyAdded = TRUE;
				}
			}
			if (!alreadyAdded) {
				[graph addPlot:dataSourceLinePlot3];
			}
			break;
			
		default:
			 break;
	} 
}

-(IBAction) datesSegCtrlIndexChanged
{
	switch (self.datesToPlot.selectedSegmentIndex) {
		case 0:
			break;
			
		case 1:
			break;
			
		case 2:
			break;
			
		default:
			break;
	} 
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
	[graph release];
	[dataForPlot release];
	[dataSourceLinePlot1 release];
	[dataSourceLinePlot2 release];
	[dataSourceLinePlot3 release];
	//[hitsPlot release];
	//[traumaPlot release];
	//[tempPlot release];
}


@end
